'''
支付宝
'''
import base64

import numpy as np
import requests
from PIL import Image

import util.img_utils as img_utils
import util.img_name_utils as img_name_utils
import model_type.zfb.my_config as my_config
import os
import time
import shutil

import util.img_connected_domain as img_connected_domain
import model_precit

def init_img(file_path):
    img = Image.open(file_path).convert("L")
    # 基本处理，灰度处理，提升识别准确率
    #     im = im.convert("L")
    return img


def cut_img(img, threshold=150):
    img = img.convert("L")
    img_np = np.asarray(img).copy()
    img_np = img_utils.remove_noise(img_np, threshold)
    img_np = img_utils.cut_white_area(img_np, threshold)
    all_imgs_no_white = img_connected_domain.img_connected_domain(img_np, threshold)

    if len(all_imgs_no_white) != 4:
        return []
    all_imgs = []
    for i in all_imgs_no_white:
        img = Image.fromarray(i.astype('uint8'))
        img = img_utils.resize(img, 32, 32).convert("L")
        all_imgs.append(img)

    return all_imgs

def format_img(im, name, newFilepath='label/tmp'):
    '''
    格式化图片
    '''
    oldNameOld = name
    oldName = name.split('-')[0].split('.')[0].lower()

    if not os.path.exists(newFilepath):
        os.makedirs(newFilepath)
    nim = cut_img(im)
    if len(nim) == 0:
        print("{}:切割失败".format(oldNameOld))
        return
    # 格式化图片名
    name = img_name_utils.format_name(name)
    if len(nim) != len(name):
        name = ['z'] * len(nim)
    for i in range(len(nim)):
        nim[i].save(newFilepath + '/' + name[i] + '-' +
                    oldName + '_' + (str(time.time())).replace(".", "") + ".png", 'png')

def format_folder(filepath, newFilepath=None):
    '''
    格式化文件夹图片
    :param filepath:
    :param newFilepath:
    :return:
    '''
    if not newFilepath:
        newFilepath = 'label/tmp'
    fileList = os.listdir(filepath)
    for i in fileList:
        if '-' in i:
            im = Image.open(filepath + '/' + i)
            format_img(im, i, newFilepath)
        else:
            os.remove(filepath + '/' + i)
            print('删除不符合名称文件[{}]'.format(i))
    print('格式化完成')

def get_tag_img():
    """
    根据url获取合适的验证码
    :return:
    """
    r = requests.get(my_config.IMG_URL).content
    base64_str = base64.b64encode(r)
    base64_str = str(base64_str, 'utf8')
    # print(base64_str)
    im = img_utils.base64_to_image(base64_str)
    # im.show()
    ims = cut_img(im.convert("L"), 150)
    if len(ims) == 0:
        return None, None
    else:
        tag = ''
        for i in ims:
            tag = tag + model_precit.predict_one_letter(i)
        return base64_str, tag

if __name__ == '__main__':


    # if os.path.exists('./test'):
    #     shutil.rmtree('test')
    #
    # os.makedirs('test')
    #
    # im = init_img('./sample/0.png')
    # ims = cut_img(im, 150)
    # if len(ims) == 0:
    #     print("切割失败")
    # for i in range(len(ims)):
    #     print(i)
    #     ims[i].save('./test/{}.png'.format(i))

    # get_tag_img()

    # print(imas)

    # ima = img_utils.remove_noise(ima, threshold)
    # ima = img_utils.cut_white_area(ima, threshold)
    # im2 = Image.fromarray(ima.astype('uint8'))
    # im2 = im2.rotate(360, expand=1, fillcolor=255)
    # im2.show()


    # ims = cut_img(im)
    # if len(ims) == 0:
    #     print("切割失败")
    # for i in range(len(ims)):
    #     print(i)
    #     ims[i].save('./test/{}.png'.format(i))

    format_folder('label/old', 'label/tmp')
    img_utils.split_train_and_test('label/tmp', my_config.train_path, my_config.test_path, my_config.char_set)
